package com.example.mcp;

import android.app.NotificationManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private boolean serverStarted = false;
    private ServiceManager serviceManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化服务管理器
        serviceManager = new ServiceManager(this);
        
        // 检查电池优化设置
        BatteryOptimizationHelper.checkAndHandleBatteryOptimization(this);
        
        // 检查网络连接
        checkNetworkAndStartServer();

        findViewById(R.id.start).setOnClickListener(v -> {
            if (!serverStarted) {
                startMcpServer();
            }
        });

        findViewById(R.id.stop).setOnClickListener(v -> {
            if (serverStarted) {
                stopMcpServer();
            }
        });

    }

    private void checkNetworkAndStartServer() {
        // 异步检查网络连接
        NetworkChecker.checkAsync(this, new NetworkChecker.Callback() {
            @Override
            public void onResult(NetworkChecker.Result result) {
                runOnUiThread(() -> {
                    if (result.localNetworkAvailable) {
                        if (result.internetReachable) {
                            Toast.makeText(MainActivity.this, "网络连接正常", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(MainActivity.this, "本地网络可用，但无法访问外网", Toast.LENGTH_LONG).show();
                        }
                    } else {
                        Toast.makeText(MainActivity.this, "无网络连接", Toast.LENGTH_LONG).show();
                    }
                });
            }
        });
    }

    private void startMcpServer() {
        // 使用服务管理器启动前台服务
        serviceManager.startMcpServerService();
        serviceManager.bindToMcpServerService();
        
        serverStarted = true;
        Toast.makeText(this, "🌤️ MCP服务器前台服务已启动！", Toast.LENGTH_SHORT).show();
    }

    private void stopMcpServer() {
        // 使用服务管理器启动前台服务
        serviceManager.unbindFromMcpServerService();
        serviceManager.stopMcpServerService();

        serverStarted = false;
        Toast.makeText(this, "🌤️ MCP服务器前台服务已停止!", Toast.LENGTH_SHORT).show();
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (serviceManager != null) {
            serviceManager.cleanup();
        }
    }
}